//
//  CorgiStatusViewModel.swift
//  weibo
//
//  Created by Corgi on 17/3/24.
//  Copyright © 2017年 cocoaHangTou. All rights reserved.
//

import UIKit

class CorgiStatusViewModel: NSObject {

    var homeModel: CorgiHomeModel? {
    
        didSet {
        
            mbrankImage = dealMbrankImage(mbrank: homeModel?.user?.mbrank ?? 0)
        
            verifiedImage = dealVerifiedImage(verified: homeModel?.user?.verified ?? 0)
            
            sourceText = dealSourceText(source: homeModel?.source)
            
            orginalAttributedString = dealContentAttributedString(text: homeModel?.text)
            
            retweetAttributedString = dealContentAttributedString(text: homeModel?.retweeted_status?.text)
        }
    }
    
    var mbrankImage: UIImage?
    
    var verifiedImage: UIImage?
    
    var sourceText: String?
    
    var createTime: String? {
    
        return dealTimeText(createAt: homeModel?.created_at)
    }
    
    var orginalAttributedString: NSMutableAttributedString?
    
    var retweetAttributedString: NSMutableAttributedString?
}

extension CorgiStatusViewModel {

    func dealContentAttributedString(text: String?) -> NSMutableAttributedString? {
        
        guard let t = text else {
            
            return nil
        }
        
        let allAttributedString = NSMutableAttributedString(string: t)
        
        let matchResult = try! NSRegularExpression(pattern: "\\[[\\w]+\\]", options: []).matches(in: t, options: [], range: NSRange(location: 0, length: t.characters.count))
        
        for match in matchResult.reversed() {
            
            let result = (t as NSString).substring(with: match.range)
            
            let emoticonModel = CorgiEmoticonTools.shared.getEmoticonModelWithEmoticons(chs: result)
            
            let allPath = emoticonModel?.allPath ?? ""
            
            let image = UIImage(named: allPath, in: CorgiEmoticonTools.shared.emoticonsBundle, compatibleWith: nil)
            
            let lineHeight = UIFont.systemFont(ofSize: FONTSIZEOFNORMAL).lineHeight
            
            let att = CorgiTextAttachment()
            
            att.image = image
            
            att.bounds = CGRect(x: 0, y: 0, width: lineHeight, height: lineHeight)
            
            let attr = NSAttributedString(attachment: att)
            
            allAttributedString.replaceCharacters(in: match.range, with: attr)
        }
        
        setTextHighlighted(pattern: "@[a-zA-Z0-9\\u4e00-\\u9fa5_\\-]+", allAttributedString: allAttributedString)
        
        setTextHighlighted(pattern: "#[^#]+#", allAttributedString: allAttributedString)
        
        setTextHighlighted(pattern: "([hH]ttp[s]{0,1})://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\-~!@#$%^&*+?:_/=<>.',;]*)?", allAttributedString: allAttributedString)
        
        return allAttributedString
    }
}

extension CorgiStatusViewModel {

    fileprivate func setTextHighlighted(pattern: String, allAttributedString: NSMutableAttributedString) {
     
        let matchResult = try! NSRegularExpression(pattern: pattern, options: []).matches(in: allAttributedString.string, options: [], range: NSRange(location: 0, length: allAttributedString.string.characters.count))
        
        for match in matchResult {
            
            let range = match.range
            
            
        }
    }
}

extension CorgiStatusViewModel {

    fileprivate func dealMbrankImage(mbrank: Int) -> UIImage? {
        
        if mbrank > 0 && mbrank < 7 {
            
            return UIImage(named: "common_icon_membership_level\(mbrank)")
            
        }
        
        return UIImage(named: "common_icon_membership")
    }

}

extension CorgiStatusViewModel {

    fileprivate func dealVerifiedImage(verified: Int) -> UIImage? {
        
        switch verified {
        case 1:
            return UIImage(named: "avatar_vip")
        case 2,3,5:
            return UIImage(named: "avatar_enterprise_vip")
        case 220:
            return UIImage(named: "avatar_grassroot")
        default:
            return UIImage(named: "avatar_vgirl")
        }
    }
}

extension CorgiStatusViewModel {

    fileprivate func dealTimeText(createAt: Date?) -> String? {
        
        guard let sinaDate = createAt else {
            return nil
        }
        
        let dateFormatter = DateFormatter()
        
        let isThisYear = dealDateIsThisYear(sinaDate: sinaDate)
        
        if isThisYear {
            
            let calendar = Calendar.current
            
            if calendar.isDateInToday(sinaDate) {
                
                let second = Int(Date().timeIntervalSince(sinaDate))
                
                if second <= 60 {
                    
                    return "刚刚"
                } else if second > 60 && second <= 60*60 {
                    
                    return "\(second / 60)分钟前"
                } else {
                    
                    return "\(second / 3600)小时前"
                }
                
                
            } else if calendar.isDateInYesterday(sinaDate) {
                
                dateFormatter.dateFormat = "昨天 hh:mm"
                
                
            } else {
                
                dateFormatter.dateFormat = "MM月dd日 hh:mm"
                
            }
        } else {
            
            dateFormatter.dateFormat = "yyyy年MM月dd日 hh:mm"
        }
        
        let result = dateFormatter.string(from: sinaDate)
        
        return result
        
    }
    
    fileprivate func dealDateIsThisYear(sinaDate: Date) -> Bool {
        
        let dateFormatter = DateFormatter()
        
        dateFormatter.dateFormat = "yyyy"
        
        let sinaDateStr = dateFormatter.string(from: sinaDate)
        
        let currentDateStr = dateFormatter.string(from: Date())
        
        return sinaDateStr == currentDateStr
    }
    
}


extension CorgiStatusViewModel {

    fileprivate func dealSourceText(source: String?) -> String {
        
        guard let s = source, s.contains("\">") else {
            
            return "来自 那遥远的地方"
        }
        
        //获取字符串光标位置
        let startIndex = s.range(of: "\">")!
        
        let endIndex = s.range(of: "</")!
        
        let result = s.substring(with: startIndex.upperBound..<endIndex.lowerBound)
        
        return "来自 " + result
    }

}
